/*
===========================================================================
This source file is part of DyLab (Dynamic Laboratory)
For the latest info, see http://dylab.googlecode.com

Copyright (c) 2006-2008 Lukas Krejci
(krejci.lukas@volny.cz)

This file is part of DyLab.

    DyLab is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DyLab is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DyLab.  If not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/

#ifndef __dylab_Plane_h__
#define __dylab_Plane_h__

//===========================================================================================
#include <dylab/utils/geometry/Ray3.h>
#include <dylab/utils/geometry/EdgeGeometry3.h>
#include <dylab/utils/exceptions/EInvalidState.h>

//===========================================================================================
namespace dylab {

    /** 
     */
    class DYLAB_EXPORT Plane 
    {
    private:       
        ///
        Vector3 mNormal;
        ///
        real_t mDisplacement;
    public:

        /**          
         */
        Plane() 
                { }

        /**
        */
        Plane(const Vector3 & _p0, const Vector3 & _p1, const Vector3 & _p2)
            : mNormal((_p1 - _p0).cross(_p2 - _p0).normalise())
                { mDisplacement = - mNormal.dot(_p0); }

        /**
        */
        Plane(const Vector3 & _normal, real_t _displacement)
            : mNormal(_normal), mDisplacement(_displacement)
                { }

        /**
        */
        Plane(const Vector3 & _normal, const Vector3 & _point)
            : mNormal(_normal), mDisplacement(-_normal.dot(_point))
                { }

        /**
        */
        Plane(const Plane & _plane) 
            : mNormal(_plane.mNormal), mDisplacement(_plane.mDisplacement)
                { }

        /** 
         */
        Plane(const ArrayReal<4> & _v)
            : mNormal(_v[0], _v[1], _v[2]), mDisplacement(_v[3])
                { } 

        /** 
         */
        const Vector3 & getNormal() const
                { return mNormal; }

        /** 
         */
        const real_t & getDisplacement() const
                { return mDisplacement; }

        /**
        */
        bool isDegenerated() const
                { return mNormal.almostZero(); }

        /**
        */
        bool isParallelTo(const Plane & _plane) const
                { return mNormal.cross(_plane.mNormal).almostZero(); }

        /**
        */
        bool testPointInside(const Vector3 & _p, real_t _tolerance = Math::EQUALITY_TOLERANCE) const
                { return Math::almostZero(mNormal.dot(_p) + mDisplacement, _tolerance); }

        /**
        */
        real_t computeSignedDistance(const Vector3 & _p)
                {
                    real_t d = mNormal.dot(mNormal);
					if (d == 0) throw EInvalidState(String::fmt("Unable to compute distance to (%1%). Invalid normal vector: (%2%)", _p, mNormal));
                    return (mNormal.dot(_p) + mDisplacement) / d;
                }

        /**
        */
        real_t computeDistance(const Vector3 & _p)
                { return abs(computeSignedDistance(_p)); }

        /**
        */
        Math::intersection_t computeLineIntersection(const Vector3 & _a, const Vector3 & _b, 
			Vector3 & _ip = Vector3(), bool allowAMinus = true, bool allowBPlus = true) const;

        /** 
         */
        Math::intersection_t computeRayIntersection(const Ray3 & _ray, Vector3 & _ip = Vector3()) const
                { return computeLineIntersection(_ray.start(), _ray.start() + _ray.direction(), _ip, false, true); }

        /** 
         */
        Math::intersection_t computeEdgeIntersection(const EdgeGeometry3 & _edge, Vector3 & _ip = Vector3()) const
                { return computeLineIntersection(_edge.vertex(EdgeGeometry3::V_0), _edge.vertex(EdgeGeometry3::V_1), _ip, false, false); }

        /**
        */
        operator String() const                
				{ return String::fmt("%1% %2%", mNormal, mDisplacement); }
    };

    //===========================================================================================    
    inline std::ostream & operator << (std::ostream & _os, const Plane & _o)
            { return _os << String(_o); }

    //===========================================================================================
    template <>
        inline Plane TypeParser::parse(const String & _string)
            { return Plane(ArrayReal<4>::parse(_string)); }
    template <>
        inline Plane TypeParser::parse(const String & _string, const Plane & _defaultValue)
            {
                try { return TypeParser::parse<Plane>(_string); }
                catch (EInvalidFormat &) { return _defaultValue; }
            }
    template <>
        inline String String::fmt(const Plane & _value)
            { return String(_value); }
            
}
//===========================================================================================
#endif // __dylab_Plane_h__
